angular.module('common.services', [])

.constant('COMMON_MSG', {
  'Internal server error': '数据有误'
})

.directive('ionMultipleSelect', ['$ionicModal', '$ionicGesture', function ($ionicModal, $ionicGesture) {
  return {
    restrict: 'E',
    scope: {
      options : "="
    },
    controller: function ($scope, $element, $attrs) {
      $scope.multipleSelect = {
        title:            $attrs.title || "Select Options",
        tempOptions:      [],
        keyProperty:      $attrs.keyProperty || "id",
        valueProperty:    $attrs.valueProperty || "value",
        selectedProperty: $attrs.selectedProperty || "selected",
        templateUrl:      $attrs.templateUrl || 'templates/multipleSelect.html',
        renderCheckbox:   $attrs.renderCheckbox ? $attrs.renderCheckbox == "true" : true,
        animation:        $attrs.animation || 'slide-in-up'
      };

      $scope.OpenModalFromTemplate = function (templateUrl) {
        $ionicModal.fromTemplateUrl(templateUrl, {
          scope: $scope,
          animation: $scope.multipleSelect.animation
        }).then(function (modal) {
          $scope.modal = modal;
          $scope.modal.show();
        });
      };

      $ionicGesture.on('tap', function (e) {
       $scope.multipleSelect.tempOptions = $scope.options.map(function(option){
         var tempOption = { };
         tempOption[$scope.multipleSelect.keyProperty] = option[$scope.multipleSelect.keyProperty];
         tempOption[$scope.multipleSelect.valueProperty] = option[$scope.multipleSelect.valueProperty];
         tempOption[$scope.multipleSelect.selectedProperty] = option[$scope.multipleSelect.selectedProperty];

         return tempOption;
       });
        $scope.OpenModalFromTemplate($scope.multipleSelect.templateUrl);
      }, $element);

      $scope.saveOptions = function(){
        for(var i = 0; i < $scope.multipleSelect.tempOptions.length; i++){
          var tempOption = $scope.multipleSelect.tempOptions[i];
          for(var j = 0; j < $scope.options.length; j++){
            var option = $scope.options[j];
            if(tempOption[$scope.multipleSelect.keyProperty] == option[$scope.multipleSelect.keyProperty]){
              option[$scope.multipleSelect.selectedProperty] = tempOption[$scope.multipleSelect.selectedProperty];
              break;
            }
          }
        }
        $scope.closeModal();
      };

      $scope.closeModal = function () {
        $scope.modal.remove();
      };
      $scope.$on('$destroy', function () {
          if ($scope.modal){
              $scope.modal.remove();
          }
      });
    }
  };
}])
//
.directive('contenteditable', function() {
  return {
    restrict: 'A', // only activate on element attribute
    require: '?ngModel', // get a hold of NgModelController
    link: function(scope, element, attrs, ngModel) {
      if(!ngModel) return; // do nothing if no ng-model

      // Specify how UI should be updated
      ngModel.$render = function() {
        element.html(ngModel.$viewValue || '');
      };

      // Listen for change events to enable binding
      element.on('blur keyup change', function() {
        scope.$apply(read);
      });
      read(); // initialize

      // Write data to the model
      function read() {
        var html = element.html();
        // When we clear the content editable the browser leaves a <br> behind
        // If strip-br attribute is provided then we strip this out
        if( attrs.stripBr && html == '<br>' ) {
          html = '';
        }
        ngModel.$setViewValue(html);
      }
    }
  };
})

.directive('reorder', function() {
  return {
    link: function(scope, element, attrs) {
      scope.order = attrs.reorder;
      scope.orderList = function(){
        scope.order = scope.order.indexOf("-")===0?scope.order.substr(1):'-'+scope.order;
      };
    }
  };
})

.directive('textFilter', function($timeout) {
  return {
    restrict: 'A',
    transclude: true,
    templateUrl: 'templates/common/model/text-filter.html',
    link: function(scope, element, attrs) {
        scope.toggleFilter = function(){
          scope.showFilter = !scope.showFilter;
          if(scope.showFilter){
            $timeout(function(){
              //input 获取焦点
              element[0].children[1].children[0].focus();
              if(ionic.Platform.isAndroid()){
                cordova.plugins.Keyboard.show();
              }
            },150);
          }
        };
        scope.setFilter = function(filter){
          scope.filter = filter;
        };
        scope.resetFilter = function(){
          scope.filter = '';
          scope.showFilter = false;
        };
      }
  };
})
//日期插件
.filter('calendar', function () {
  return function (time) {
    if (!time) return;

    return moment(time).calendar(null, {
      lastDay : '[昨天]',
      nextDay: '[明天]',
      sameDay : 'LT',
      lastWeek : '[上]dddd',
      nextWeek: '[下]dddd',
      sameElse : 'YY-MM-DD'
    });
  };
})

.filter('numFormat', function () {

  return function (str,currency) {
    if (!str) return;
    var strArray = str.split(',');
    // console.log(str,strArray);
    var index = currency? 1:0;
    var result='';

    if(strArray.length<=2){
      return str;
    // 大于百万
    }else if(strArray.length===3){
      switch(strArray[0].length){
        case 2:
          result = strArray[0] + '百万';
          break;
        case 3:
          result = strArray[0].slice(0,index+1) + '千万';
          break;
        case 4:
          result = strArray[0].slice(0,index+1) + '亿';
      }
      //大于十亿
    }else if(strArray.length>=4){
      //删除最后两个
      strArray.splice(strArray.length-2,2);
      // 1亿到1百万分位，只保留亿位
      strArray[strArray.length-1]=strArray[strArray.length-1].charAt(0);
      // 连接字符
      result = strArray.join('') + '亿';
    }

    return result;
  };
})

//通讯录
.service("ContactManager", function($q,$cordovaContacts) {
  var contacts=[]; //variable that holds contacts, returned from getContacts
  var formatContact = function(contact) {
    var formattedContact =  {
      "name"   : contact.displayName || contact.name.formatted || contact.name.familyName + contact.name.givenName || "姓名未知",
      "emails"        : contact.emails || [],
      "phones"        : contact.phoneNumbers || [],
      "organizations" : contact.organizations || []
    };
    // 格式清理
    formattedContact.name = formattedContact.name.trim();
    formattedContact.phones.forEach(function(p){
      p.id=undefined;
      p.pref=undefined;
    });
    formattedContact.emails.forEach(function(em){
      em.id=undefined;
      em.pref=undefined;
    });

    return formattedContact;
  };
  var getContacts = function() {
    var deferred = $q.defer();
    if($cordovaContacts) {
      // 不传参导致找不到对象，field错误
      var options = {
        filter : "",
        multiple : true
      };
      $cordovaContacts.find(options).then(function(contactsFromNav){
        contactsFromNav.forEach(function(contact){
          contacts.push(formatContact(contact));
        });
          deferred.resolve( contacts );
      });
    } else {
        deferred.reject("无联系人");
    }
    return deferred.promise;
  };

  return {
      getContacts : getContacts
  };

})

//html过滤器
.filter('to_trusted', function ($sce) {
  return function (text) {
      return $sce.trustAsHtml(text);
  };
})
//删除所有HTML标签、空白、换行
.filter('delHtmlTag', function () {
  return function (text,repType) {
    if(!text) return;
    var regMap ={
      'a':new RegExp("</?a[^>]*>","ig"),
      'html':new RegExp("<[^>]+>\n*\s*\t*\r*","ig"),
      'blank':new RegExp("　*","ig")
    };
    // 传入参数可以是字符串
    if(typeof repType == 'string'){
      return text.replace(regMap[repType],"");
    }else if(repType instanceof Array){
      repType.forEach(function(t){
        text = text.replace(regMap[t],"");
      });
      return text;
    }
  };
})

//input获得焦点
.directive('autoFocus', function($log, $timeout) {
  return {
    restrict: 'A',
    link: function(scope, element,ctrl) {

      //点击编辑按钮时触发focus
      scope.$watch('$root.isEdit', function(newValue) {
        if (newValue) {
           $timeout(function(){
              element[0].focus();
              if(ionic.Platform.isAndroid()){
                cordova.plugins.Keyboard.show();
              }
           },150);
        }

      });

    }
  };
})

.directive('autoFocus1', function() {
  return {
    link: function(scope, element, attrs) {
      $timeout(function() {
        element[0].focus();
        if(ionic.Platform.isAndroid()){
           cordova.plugins.Keyboard.show();
        }
      }, 150);
    }
  };
})

.directive('autoFocus2', function() {

  return {
    restrict: 'A',
    require: '^^ionNavView',
    link: function(scope, el, attrs, ctrl) {
      ctrl.scope.$on('$ionicView.afterEnter', function() {
        el[0].focus();
      });
    }
  };
})

  // 出错弹窗
.factory('PopupService', function ($ionicPopup) {
  return {
    showAlert: function(msg) {
      var alertPopup = $ionicPopup.alert({
        title: '出错啦！',
        okType:'button-royal',
        template: msg
      });
      alertPopup.then(function(res) {
      });
    }
  };
})

.factory('ToastService', function ($cordovaToast) {
  return {
    show: function(msg) {
      if (window.cordova && window.cordova.plugins) {   // && window.cordova.plugins.Keyboard
        $cordovaToast.showShortCenter(msg);
      }
    }
  };
});
